package com.appsys.controller;

import com.appsys.pojo.*;
import com.appsys.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @ClassName AddAppInfoController
 * @Description TODO
 * @Author YinLiangTao Email:1517535831@qq.com
 * @Date 2022/3/1 15:09
 * @Version 1.0
 */
@Controller
public class AppInfoController {
    @Resource
    private StatusService statusService;
    @Resource
    private FlatformService flatformService;
    @Resource
    private FirstLevelService firstLevelService;
    @Resource
    private SecondLevelService secondLevelService;
    @Resource
    private ThirdLevelService thirdLevelService;
    @Resource
    private AppInfoService appInfoService;
    @Resource
    private DevService devService;
    @Resource
    private VersionService versionService;

    //跳转添加app信息页面
    @RequestMapping(value = "/toAddAppInfo/{devId}")
    public String toAddAppInfo(@PathVariable(value = "devId") int devId, Model model) {
        Dev dev = devService.getDevById(devId);
        model.addAttribute("devId", devId);
        model.addAttribute("devName", dev.getDevName());
        //获取全部的状态信息
        List<Status> status = statusService.getStatus();
        model.addAttribute("status", status);
        //获取全部的平台信息
        List<Flatform> flatforms = flatformService.getFlatforms();
        model.addAttribute("flatforms", flatforms);
        //获取全部的一级分类
        List<FirstLevel> firstLevels = firstLevelService.getFirstLevels();
        model.addAttribute("firstLevels", firstLevels);
        return "addAppInfo";
    }

    //跳转修改app信息页面
    @RequestMapping(value = "/toModifyAppInfo/{devId}/{id}")
    public String toModifyAppInfo(@PathVariable(value = "devId") int devId, @PathVariable(value = "id") int id, Model model) {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("devId", devId);
        map.put("id", id);
        Dev dev = devService.getDevById(devId);
        model.addAttribute("devName", dev.getDevName());
        List<AppInfo> appInfoByDevId = appInfoService.getAppInfoByDevId(map);
        String logoPath = appInfoByDevId.get(0).getLogoPath();
        if (logoPath != null) {
            logoPath.replace("\\", "\\u005c\\u005c");
            File file = new File(logoPath);
            String logoPathName = file.getName();
            model.addAttribute("logoPathImg", "static/uploadfiles/" + logoPathName);
        }
        model.addAttribute("appInfo", appInfoByDevId);
        //获取全部的状态信息
        List<Status> status = statusService.getStatus();
        model.addAttribute("status", status);
        //获取全部的平台信息
        List<Flatform> flatforms = flatformService.getFlatforms();
        model.addAttribute("flatforms", flatforms);
        //获取全部的一级分类
        List<FirstLevel> firstLevels = firstLevelService.getFirstLevels();
        model.addAttribute("firstLevels", firstLevels);
        //获取二级分类
        List<SecondLevel> secondLevels = secondLevelService.getSecondLevels(appInfoByDevId.get(0).getCategoryLevel1().getId());
        model.addAttribute("secondLevels", secondLevels);
        List<ThirdLevel> thirdLevels = thirdLevelService.getThirdLevels(appInfoByDevId.get(0).getCategoryLevel2().getId());
        model.addAttribute("thirdLevels", thirdLevels);
        return "modifyAppInfo";
    }

    //跳转app所有的信息页面
    @RequestMapping(value = "/toAppInfoAndVersion/{devId}/{id}/{versionId}/{pageNumber}")
    public String toAppInfoAndVersion(@PathVariable(value = "devId") int devId, @PathVariable(value = "id") int id,
                                      @PathVariable(value = "versionId") int versionId,
                                      @PathVariable(value = "pageNumber") int pageNumber, Model model) {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("devId", devId);
        map.put("id", id);
        List<AppInfo> appInfoByDevId = appInfoService.getAppInfoByDevId(map);
        String logoPath = appInfoByDevId.get(0).getLogoPath();
        if (logoPath != null) {
            logoPath.replace("\\", "\\u005c\\u005c");
            File file = new File(logoPath);
            String logoPathName = file.getName();
            model.addAttribute("logoPathImg", "static/uploadfiles/" + logoPathName);
        }
        model.addAttribute("appInfo", appInfoByDevId);

        List<Version> versions = versionService.getVersionByAppId(id);
        Dev dev = devService.getDevById(devId);
        model.addAttribute("devName", dev.getDevName());
        model.addAttribute("versions", versions);
        model.addAttribute("devId", devId);
        model.addAttribute("id", id);
        model.addAttribute("pageNumber", pageNumber);
        return "appInfoAndVersion";
    }

    //添加app信息
    @RequestMapping(value = "/appInfo/{devId}", method = RequestMethod.POST)
    public String addAppInfo(@PathVariable(value = "devId") int devId,
                             @RequestParam(value = "logoPath") MultipartFile logoPath,
                             @RequestParam(value = "softwareName") String softwareName,
                             @RequestParam(value = "apkName") String apkName,
                             @RequestParam(value = "supportRom") String supportRom,
                             @RequestParam(value = "interfaceLanguage") String interfaceLanguage,
                             @RequestParam(value = "sofewareSize") double sofewareSize,
                             @RequestParam(value = "downloads") int downloads,
                             @RequestParam(value = "flatformId") int flatformId,
                             @RequestParam(value = "categoryLevel1") int categoryLevel1,
                             @RequestParam(value = "categoryLevel2") int categoryLevel2,
                             @RequestParam(value = "categoryLevel3") int categoryLevel3,
                             @RequestParam(value = "status") String status,
                             @RequestParam(value = "appInfo") String appInfo,
                             HttpServletRequest request, Model model) {
        String idPicPath = null;
        //判断文件是否为空
        if (!logoPath.isEmpty()) {
            //上传的路径
            String path = request.getSession().getServletContext().getRealPath("static" + File.separator + "uploadfiles");
            String oldFileName = logoPath.getOriginalFilename();//源文件名
            String prefix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1, oldFileName.length());//获取后缀名
            int filesize = 5000000;
            if (logoPath.getSize() > filesize) {//上传文件不大于5000kB
                request.setAttribute("uploadFileError", "*上传文件不得大于5000kB");
                return "redirect:/toAddAppInfo/" + devId;
            } else if (prefix.equalsIgnoreCase("jpg")
                    || prefix.equalsIgnoreCase("jepg")
                    || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("ico")) {
                String fileName = System.currentTimeMillis() + (int) (Math.random() * 1001) + "_logo.jpg";
                //在指定条件下创建一个文件
                File file = new File(path, fileName);
                if (!file.exists()) {
                    file.mkdirs();
                }
                ////将文件保存到服务器指定位置
                try {
                    logoPath.transferTo(file);
                } catch (IOException e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", "*上传失败");
                    return "redirect:/toAddAppInfo/" + devId;
                }
                idPicPath = path + File.separator + fileName;
            } else {
                request.setAttribute("uploadFileError", "*上传图片格式不正确");
                return "redirect:/toAddAppInfo/" + devId;
            }
        }
        AppInfo app = new AppInfo();
        app.setLogoPath(idPicPath);
        app.setSoftwareName(softwareName);
        app.setApkName(apkName);
        app.setSupportRom(supportRom);
        app.setAppInfo(appInfo);
        app.setDevId(devId);
        app.setDownloads(downloads);
        app.setStatus(new Status(1, status));
        app.setSofewareSize(sofewareSize);
        app.setCategoryLevel1(new FirstLevel(categoryLevel1, ""));
        app.setCategoryLevel2(new SecondLevel(categoryLevel2, ""));
        app.setCategoryLevel3(new ThirdLevel(categoryLevel3, ""));
        app.setInterfaceLanguage(interfaceLanguage);
        app.setUpdateDate(new Date());
        app.setFlatform(new Flatform(flatformId, ""));
        // app.setVersionId(versionId);
        System.out.println(app);
        if (appInfoService.addInfo(app)) {
            return "redirect:/list/" + devId + "/1";
        }
        return "redirect:/toAddAppInfo/" + devId;
    }

    //更新app信息
    @RequestMapping(value = "/appInfo/{devId}/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    public String updateAppInfo(@PathVariable(value = "devId") int devId,
                                @PathVariable(value = "id") int id,
                                @RequestParam(value = "logoPath", required = false) MultipartFile logoPath,
                                @RequestParam(value = "logoPathImg", required = false) String logoPathImg,
                                @RequestParam(value = "saveAndCommit", required = false, defaultValue = "0") Integer saveAndCommit,
                                @RequestParam(value = "softwareName") String softwareName,
                                @RequestParam(value = "apkName") String apkName,
                                @RequestParam(value = "supportRom") String supportRom,
                                @RequestParam(value = "interfaceLanguage") String interfaceLanguage,
                                @RequestParam(value = "sofewareSize") double sofewareSize,
                                @RequestParam(value = "downloads") int downloads,
                                @RequestParam(value = "flatformId") int flatformId,
                                @RequestParam(value = "categoryLevel1") int categoryLevel1,
                                @RequestParam(value = "categoryLevel2") int categoryLevel2,
                                @RequestParam(value = "categoryLevel3") int categoryLevel3,
                                @RequestParam(value = "status") String status,
                                @RequestParam(value = "appInfo") String appInfo,
                                HttpServletRequest request, Model model) {
        String idPicPath = null;
        //判断文件是否为空
        if (!logoPath.isEmpty()) {
            //上传的路径
            String path = request.getSession().getServletContext().getRealPath("static" + File.separator + "uploadfiles");
            String oldFileName = logoPath.getOriginalFilename();//源文件名
            String prefix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1, oldFileName.length());//获取后缀名
            int filesize = 5000000;
            if (logoPath.getSize() > filesize) {//上传文件不大于5000kB
                request.setAttribute("uploadFileError", "*上传文件不得大于5000kB");
                return "redirect:/toModifyAppInfo/" + devId + "/" + id;
            } else if (prefix.equalsIgnoreCase("jpg")
                    || prefix.equalsIgnoreCase("jepg")
                    || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("ico")) {
                String fileName = System.currentTimeMillis() + (int) (Math.random() * 1001) + "_logo.jpg";
                //在指定条件下创建一个文件
                File file = new File(path, fileName);
                if (!file.exists()) {
                    file.mkdirs();
                }
                ////将文件保存到服务器指定位置
                try {
                    logoPath.transferTo(file);
                } catch (IOException e) {
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", "*上传失败");
                    return "redirect:/toModifyAppInfo/" + devId + "/" + id;
                }
                idPicPath = path + File.separator + fileName;

            } else {
                request.setAttribute("uploadFileError", "*上传图片格式不正确");
                return "redirect:/toModifyAppInfo/" + devId + "/" + id;
            }
        }
        AppInfo app = new AppInfo();
        app.setId(id);
        if (idPicPath != null) {
            app.setLogoPath(idPicPath);
        } else {
            app.setLogoPath(logoPathImg);
        }
        app.setSoftwareName(softwareName);
        app.setApkName(apkName);
        app.setSupportRom(supportRom);
        app.setAppInfo(appInfo);
        app.setDevId(devId);
        app.setDownloads(downloads);
        if (saveAndCommit != 0) {
            app.setStatus(new Status(1, status));
        } else {
            List<Status> status1 = statusService.getStatus();
            for (Status status2 : status1) {
                if (status2.getStatus().equals(status)) {
                    app.setStatus(status2);
                    break;
                }
            }
        }

        app.setSofewareSize(sofewareSize);
        app.setCategoryLevel1(new FirstLevel(categoryLevel1, ""));
        app.setCategoryLevel2(new SecondLevel(categoryLevel2, ""));
        app.setCategoryLevel3(new ThirdLevel(categoryLevel3, ""));
        app.setInterfaceLanguage(interfaceLanguage);
        app.setUpdateDate(new Date());
        app.setFlatform(new Flatform(flatformId, ""));
        Integer versionId = null;
        app.setVersionId(versionId);
        if (appInfoService.updateInfo(app)) {
            return "redirect:/list/" + devId + "/1";
        }
        System.out.println("error");
        return "redirect:/toModifyAppInfo/" + devId + "/" + id;
    }

    //删除app以及其所有的版本信息
    @RequestMapping(value = "/deleteApp/{devId}/{id}/{pageNumber}/{size}")
    public String deleteApp(@PathVariable(value = "devId") int devId,
                            @PathVariable(value = "id") int id,
                            @PathVariable(value = "pageNumber") int pageNumber,
                            @PathVariable(value = "size") int size,Model model) {
        appInfoService.deleteInfo(id);
        versionService.deleteVersionByAppId(id);
        if(size == 1 && pageNumber != 1){
            pageNumber--;
        }
        return "redirect:/listWithAjax/" + devId + "/" + pageNumber;
    }

    //更新app状态
    @RequestMapping(value = "/updateStatus/{devId}/{id}/{pageNumber}/{statusId}")
    public String updateStatus(@PathVariable(value = "devId") int devId,
                               @PathVariable(value = "id") int id,
                               @PathVariable(value = "pageNumber") int pageNumber,
                               @PathVariable(value = "statusId") int statusId,
                               Model model){
        appInfoService.updateStatus(statusId,id);
        return "redirect:/listWithAjax/" + devId + "/" + pageNumber;
    }
}
